package cn.i7baozh.cloud.consumer.feign.controller;

import cn.i7baozh.cloud.api.dto.ReturnResponse;
import cn.i7baozh.cloud.consumer.feign.service.RemotePayService;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import jakarta.annotation.Resource;
import org.apache.hc.core5.concurrent.CompletedFuture;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

/**
 * @author zhangbaoqi532
 * @date 2024/12/26
 */
@RestController
public class ConsumerCircuitBreakerController {

    @Resource
    private RemotePayService remotePayService;

    @CircuitBreaker(name = "cloud-provider-payment", fallbackMethod = "circuitBreakerFallback")
    @GetMapping(value = "/consumer/circuitBreaker/{id}")
    public ReturnResponse<String> getServerInfo(@PathVariable("id") Integer id) {
        return remotePayService.circuitBreaker(id);
    }

    public ReturnResponse<String> circuitBreakerFallback(Throwable t) {
        return ReturnResponse.fail("299", "系统繁忙，请稍后重试");
    }

//    @Bulkhead(name = "cloud-provider-payment", fallbackMethod = "circuitBreakerFallback", type = Bulkhead.Type.SEMAPHORE)
//    @GetMapping(value = "/consumer/bulkhead/{id}")
//    public ReturnResponse<String> bulkhead(@PathVariable("id") Integer id) {
//        return remotePayService.circuitBreaker(id);
//    }

    @Bulkhead(name = "cloud-provider-payment", fallbackMethod = "circuitBreakerPoolFallback", type = Bulkhead.Type.THREADPOOL)
    @GetMapping(value = "/consumer/bulkhead/{id}")
    public CompletableFuture<ReturnResponse<String>> bulkheadPool(@PathVariable("id") Integer id) {
        return CompletableFuture.supplyAsync(() -> remotePayService.circuitBreaker(id));
    }
    public CompletableFuture<ReturnResponse<String>> circuitBreakerPoolFallback(Throwable t) {
        return CompletableFuture.supplyAsync(() -> ReturnResponse.fail("299", "系统繁忙，请稍后重试"));
    }

    @RateLimiter(name = "cloud-provider-payment", fallbackMethod = "circuitBreakerFallback")
    @GetMapping(value = "/consumer/ratelimit/{id}")
    public ReturnResponse<String> ratelimit(@PathVariable("id") Integer id) {
        return remotePayService.circuitBreaker(id);
    }


}
